import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class ThreadPool {
    public static void main(String[] args) throws Exception {
        ThreadPool threadPool = new ThreadPool();
        threadPool.threadTest(threadPool,"test",3);
        System.out.println("finfish");

    }

        public Boolean threadTest(Object targetObject,String methodName,Integer maxThread) throws InterruptedException, InvocationTargetException, IllegalAccessException {

            Method[] targetObjectMethodList = targetObject.getClass().getMethods();
            Method method = null;
            for (Method methodItem : targetObjectMethodList) {
                if(methodItem.getName().equals(methodName)){
                    method = methodItem;
                }
            }

            CountDownLatch countDownLatch = new CountDownLatch(maxThread);
            ExecutorService executorService = Executors.newFixedThreadPool(maxThread);

            long start = System.currentTimeMillis();
            for (int i = 0; i < maxThread; i++) {
                Method finalMethod = method;
                executorService.submit(() -> {
                    try {
                        try {
                            finalMethod.invoke(targetObject,Thread.currentThread().getName());
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    } finally {
                        System.out.println("finally");
                        countDownLatch.countDown();
                    }
                });
            }
            countDownLatch.await();
            System.out.println("任务执行完毕，继续执行主线程任务。\n耗时ms：" + (System.currentTimeMillis() - start));
            // 不要忘记关闭线程池，不然会导致主线程阻塞无法退出
            executorService.shutdown();
            return true;
        }

        public boolean test(String threadName) throws InterruptedException {
            for (int i = 0; i < 3; i++) {
                System.out.println(threadName + "执行test方法" + String.valueOf(i));
            }

            return true;
        }
}
